package Stack.ReversePolishNotation;

import Stack.Stack.Stack;

/*
    利用栈求逆波兰表达式的值（认为传入的逆波兰表达式没有错误）
    ①遇到数字，压栈；
    ②遇到操作符，弹出两个元素，[ 第二个操作数 ] 操作符 [ 第一个操作数 ]，将新的值再压回栈中；
    ③遍历结束时弹出栈中元素(正确的逆波兰表达式运算到最后栈中只会剩一个元素)
 */
public class CalculateReversePolishNotation {
    public static void main(String[] args) {
        // 3 * ( 17 - 15 ) + 18 / 6 = 9
        String[] notation = {"3", "17","15","-","*","18","6","/","+"};
        System.out.println(calculate(notation));
    }

    public static int calculate(String[] s) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < s.length; i++) {
            Integer one;
            Integer two;
            switch (s[i]) {
                case "+":
                    one = stack.pop();
                    two = stack.pop();
                    stack.push(two + one);
                    break;
                case "-":
                    one = stack.pop();
                    two = stack.pop();
                    stack.push(two - one);
                    break;
                case "*":
                    one = stack.pop();
                    two = stack.pop();
                    stack.push(two * one);
                    break;
                case "/":
                    one = stack.pop();
                    two = stack.pop();
                    stack.push(two / one);
                    break;
                default:
                    stack.push(Integer.parseInt(s[i]));
                    break;
            }
        }
        return stack.pop();
    }
}
